package com.vrp3d.security.realm;

import com.vrp3d.domain.po.User;
import com.vrp3d.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 普通用户名登录realm
 *
 * @author vrp3d
 */
public class CustomShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    public Class getAuthenticationTokenClass() {
        return super.getAuthenticationTokenClass();
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //login接口以及验证了用户是否存在,走到这里用户一定存在
        User user = userService.findByMobile(token.getUsername());
        if (null == user) {
            user = userService.findByEmail(token.getUsername());
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }
}